package com.example.doer.reading.AppActivities;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.ab.image.AbImageLoader;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbFileUtil;
import com.ab.util.AbImageUtil;
import com.ab.util.AbLogUtil;
import com.ab.util.AbStrUtil;
import com.ab.util.AbToastUtil;
import com.example.doer.reading.R;
import com.example.doer.reading.global.MyApplication;
import com.example.doer.reading.myHome.layout.SmartRefreshLayout;
import com.example.doer.reading.myHome.layout.api.RefreshHeader;
import com.example.doer.reading.myHome.layout.api.RefreshLayout;
import com.example.doer.reading.myHome.layout.listener.OnRefreshListener;
import com.example.doer.reading.myHome.layout.listener.SimpleMultiPurposeListener;
import com.example.doer.reading.myHome.layout.util.DensityUtil;
import com.example.doer.reading.util.HttpImageTools;
import com.example.doer.reading.util.StatusBarUtil;
import com.flyco.roundview.RoundTextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.ab.util.AbToastUtil.showToast;
import static com.example.doer.reading.global.MyApplication.user;

/**
 * 微博列表
 */
public class MyHomeActivity extends AbActivity {

    private int num_of_focus = 0;
    private int num_of_answers = 0;
    private int mOffset = 0;
    private int mScrollY = 0;
    private AbHttpUtil abHttpUtil=null;
    private AbImageLoader abImageLoader;
    private String UserID;

    private RoundTextView Attention;
    private TextView tv_nickname;
    private TextView tv_signature;
    private CircleImageView big_Image;
    private CircleImageView small_Image;
    private TextView small_name;
    private ImageView background;
    private TextView numfocus;
    private TextView numanswers;
    private SmartRefreshLayout smartRefreshLayout;
    private LinearLayout linearLayout;
    private TextView cancleRegist;

    private File file;
    /* 用来标识请求照相功能的activity */
    private static final int CAMERA_WITH_DATA = 3023;
    /* 用来标识请求gallery的activity */
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    /* 用来标识请求裁剪图片后的activity */
    private static final int CAMERA_CROP_DATA = 3022;

    /* 拍照的照片存储位置 */
    private File PHOTO_DIR = null;
    // 照相机拍照得到的图片
    private File mCurrentPhotoFile;
    private String mFileName;
    private View mAvatarView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_practice_weibo);

        cancleRegist= (TextView) findViewById(R.id.cancleReg);
        UserID=getIntent().getStringExtra("UserID");
        if (UserID==null){
            cancleRegist.setVisibility(View.VISIBLE);
            UserID= user.getUserID();
        }else {
            cancleRegist.setVisibility(View.INVISIBLE);
        }
        abImageLoader=AbImageLoader.getInstance(this);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        smartRefreshLayout= (SmartRefreshLayout) findViewById(R.id.refreshLayout);

        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                HomehttpGet();
            }
        });

        //关注的TextView
        Attention = (RoundTextView) findViewById(R.id.attention);
        //昵称的TextView
        tv_nickname = (TextView)findViewById(R.id.nickname);

        //个性签名的TextView
        tv_signature = (TextView)findViewById(R.id.signature);

        big_Image = (CircleImageView)findViewById(R.id.avatar);

        small_Image = (CircleImageView) findViewById(R.id.toolbar_avatar);

        small_name = (TextView)findViewById(R.id.title);

        background = (ImageView) findViewById(R.id.parallax);

        numfocus = (TextView)findViewById(R.id.tv_num_of_attention);

        numanswers = (TextView) findViewById(R.id.tv_num_of_fans);

        big_Image.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (UserID==MyApplication.user.getUserID()){
                    mAvatarView = mInflater.inflate(R.layout.choose_avatar, null);
                    Button albumButton = (Button)mAvatarView.findViewById(R.id.choose_album);
                    Button camButton = (Button)mAvatarView.findViewById(R.id.choose_cam);
                    Button cancelButton = (Button)mAvatarView.findViewById(R.id.choose_cancel);
                    albumButton.setOnClickListener(new View.OnClickListener(){

                        @Override
                        public void onClick(View v) {
                            AbDialogUtil.removeDialog(MyHomeActivity.this);
                            // 从相册中去获取
                            try {
                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                                intent.setType("image/*");
                                startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
                            } catch (ActivityNotFoundException e) {
                                AbToastUtil.showToast(MyHomeActivity.this,"没有找到照片");
                            }
                        }

                    });

                    camButton.setOnClickListener(new View.OnClickListener(){

                        @Override
                        public void onClick(View v) {
                            AbDialogUtil.removeDialog(MyHomeActivity.this);
                            doPickPhotoAction();
                        }

                    });

                    cancelButton.setOnClickListener(new View.OnClickListener(){

                        @Override
                        public void onClick(View v) {
                            AbDialogUtil.removeDialog(MyHomeActivity.this);
                        }

                    });
                    AbDialogUtil.showDialog(mAvatarView, Gravity.BOTTOM);
                }
                return false;
            }
        });



        cancleRegist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyApplication.user.setLoginUser(false);
                Intent intent=new Intent(MyHomeActivity.this,RegistActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                MyHomeActivity.this.finish();
            }
        });

        //状态栏透明和间距处理
        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);

        final View parallax = findViewById(R.id.parallax);
        final View buttonBar = findViewById(R.id.buttonBarLayout);
        final NestedScrollView scrollView = (NestedScrollView)findViewById(R.id.scrollView);
        final RefreshLayout refreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        //页眉图片


        refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int bottomHeight, int extendHeight) {
                mOffset = offset / 2;
                parallax.setTranslationY(mOffset - mScrollY);
                toolbar.setAlpha(1 - Math.min(percent, 1));
            }
            @Override
            public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int bottomHeight, int extendHeight) {
                mOffset = offset / 2;
                parallax.setTranslationY(mOffset - mScrollY);
                toolbar.setAlpha(1 - Math.min(percent, 1));
            }
        });
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            private int lastScrollY = 0;
            private int h = DensityUtil.dp2px(170);
            private int color = ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary)&0x00ffffff;
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (lastScrollY < h) {
                    scrollY = Math.min(h, scrollY);
                    mScrollY = scrollY > h ? h : scrollY;
                    buttonBar.setAlpha(1f * mScrollY / h);
                    toolbar.setBackgroundColor(((255 * mScrollY / h) << 24) | color);
                    parallax.setTranslationY(mOffset - mScrollY);
                 }
                lastScrollY = scrollY;
            }
        });
        buttonBar.setAlpha(0);
        toolbar.setBackgroundColor(0);

        linearLayout = (LinearLayout) findViewById(R.id.dynamic_liner);

        abHttpUtil= AbHttpUtil.getInstance(this);

        HomehttpGet();

    }

    public void HomehttpGet(){
        String imageUrl="http://192.168.191.1/Reading/ImageDoServlet?Action=download&Category=UserLogo&ImageName="+UserID;
        abImageLoader.display(small_Image,imageUrl,360,360);
        abImageLoader.display(big_Image,imageUrl,360,360);
        final String url="http://192.168.191.1/Reading/InfoDoServlet?Action=down&UserID="+UserID;
        abHttpUtil.get(url, new AbStringHttpResponseListener() {
            @Override
            public void onSuccess(int i, String s) {
                try {
                    JSONObject jsonObject=new JSONObject(s);
                    JSONObject object=jsonObject.getJSONObject("user");
                    JSONArray jsonArray=object.getJSONArray("userActions");
                    String userName=object.getString("UserName");
                    tv_nickname.setText(userName);
                    small_name.setText(userName);
                    tv_signature.setText(object.getString("UserDescription"));
                    linearLayout.removeAllViewsInLayout();
                    for (int j=0;j<jsonArray.length();j++){
                        JSONObject action=jsonArray.getJSONObject(j);
                        linearLayout.addView(addChild(action.getString("ActionDate"),
                                action.getString("value"),
                                action.getString("actionType")));
                    }
                    numfocus.setText(String.valueOf(num_of_focus));
                    numanswers.setText(String.valueOf(num_of_answers));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {
                smartRefreshLayout.finishRefresh();
            }

            @Override
            public void onFailure(int i, String s, Throwable throwable) {
                smartRefreshLayout.finishRefresh();
                showToast(MyHomeActivity.this,"加载失败");
            }
        });
    }



    private LinearLayout addChild(String tv_Time,String tv_Discription,String action)
    {
        LayoutInflater inflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout child = (LinearLayout) inflater.inflate(R.layout.myhome_child_layout,null);
        TextView tv_time = (TextView)child.findViewById(R.id.tv_time);
        TextView tv_title = (TextView)child.findViewById(R.id.tv_title);
        TextView tv_discription = (TextView)child.findViewById(R.id.tv_discription);

        tv_time.setText(tv_Time);
        //tv_title.setText(tv_Title);
        tv_discription.setText(tv_Discription);
        final ImageView imageView = (ImageView)child.findViewById(R.id.testImage);
        switch (action){
            case "thumbUpAnswer":
                imageView.setImageResource(R.mipmap.thumbup);
                tv_title.setText("点赞文章");
                break;
            case "collectBook":
                imageView.setImageResource(R.mipmap.collect);
                tv_title.setText("收藏图书");
                break;
            case"collectAnswer":
                imageView.setImageResource(R.mipmap.collect);
                tv_title.setText("收藏文章");
                break;
            case"replyAnswer":
                imageView.setImageResource(R.mipmap.reply);
                tv_title.setText("回复文章");
                num_of_answers++;
                break;
            case"commentBook":
                imageView.setImageResource(R.mipmap.comment);
                tv_title.setText("评论书籍");
                break;
            case"focusTopic":
                imageView.setImageResource(R.mipmap.focus);
                tv_title.setText("关注话题");
                num_of_focus++;
                break;
            case"focusQuestion":
                imageView.setImageResource(R.mipmap.focus);
                tv_title.setText("关注问题");
                num_of_focus++;
                break;

        }
        return child;
    }
    /**
     * 从照相机获取
     */
    private void doPickPhotoAction() {
        String status = Environment.getExternalStorageState();
        //判断是否有SD卡,如果有sd卡存入sd卡在说，没有sd卡直接转换为图片
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            doTakePhoto();
        } else {
            AbToastUtil.showToast(MyHomeActivity.this,"没有可用的存储卡");
        }
    }
    /**
     * 拍照获取图片
     */
    protected void doTakePhoto() {
        try {
            mFileName = System.currentTimeMillis() + ".jpg";
            mCurrentPhotoFile = new File(PHOTO_DIR, mFileName);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (Exception e) {
            AbToastUtil.showToast(MyHomeActivity.this,"未找到系统相机程序");
        }
    }

    /**
     * 描述：因为调用了Camera和Gally所以要判断他们各自的返回情况,
     * 他们启动时是这样的startActivityForResult
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent mIntent) {
        if (resultCode != RESULT_OK){
            return;
        }
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA:
                Uri uri = mIntent.getData();
                String currentFilePath = getPath(uri);
                if(!AbStrUtil.isEmpty(currentFilePath)){
                    Intent intent1 = new Intent(this, CropImageActivity.class);
                    intent1.putExtra("PATH", currentFilePath);
                    startActivityForResult(intent1, CAMERA_CROP_DATA);
                }else{
                    AbToastUtil.showToast(MyHomeActivity.this,"未在存储卡中找到这个文件");
                }
                break;
            case CAMERA_WITH_DATA:
                AbLogUtil.d(testActivity.class, "将要进行裁剪的图片的路径是 = " + mCurrentPhotoFile.getPath());
                String currentFilePath2 = mCurrentPhotoFile.getPath();
                Intent intent2 = new Intent(this, CropImageActivity.class);
                intent2.putExtra("PATH",currentFilePath2);
                startActivityForResult(intent2,CAMERA_CROP_DATA);
                break;
            case CAMERA_CROP_DATA:
                String path = mIntent.getStringExtra("PATH");
                AbLogUtil.d(testActivity.class, "裁剪后得到的图片的路径是 = " + path);
                //Bitmap bitmap = AbImageBaseCache.getInstance().getBitmap(path);
                Bitmap mBitmap = AbFileUtil.getBitmapFromSD(new File(path), AbImageUtil.SCALEIMG, 116,116);
                big_Image.setImageBitmap(mBitmap);

                file =new File(path);
                new Thread(networkTask).start();

//               mImagePathAdapter.addItem(mImagePathAdapter.getCount()-1,path);
//                camIndex++;
                break;
        }
    }

    /**
     * 从相册得到的url转换为SD卡中图片路径
     */
    public String getPath(Uri uri) {
        if(AbStrUtil.isEmpty(uri.getAuthority())){
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        return path;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");
            Log.i("mylog", "请求结果为-->" + val);
            // TODO
            // UI界面的更新等相关操作
        }
    };


    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            HttpImageTools.uploadFile(file,"UserLogo",MyApplication.user.getUserID());
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("value", "请求结果");
            msg.setData(data);
            handler.sendMessage(msg);
        }
    };



}
